package com.zhao.dota.security.integration.authenticator;

import com.zhao.dota.bo.AuthenticateUser;
import com.zhao.dota.contant.LoginConstant;
import com.zhao.dota.model.User;
import com.zhao.dota.security.integration.IntegrationAuthentication;
import com.zhao.dota.service.WechatService;
import com.zhao.dota.struct.WechatSession;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 默认登录处理
 **/
@Component
@Primary
public class WechatAuthenticator extends AbstractPreparableIntegrationAuthenticator {

    private static final String AUTH_TYPE = "wechat";

    @Resource
    private WechatService wechatService;

    @Override
    public AuthenticateUser authenticate(IntegrationAuthentication integrationAuthentication) {
        String code = integrationAuthentication.getAuthParameter(LoginConstant.CODE_PARAM);
        WechatSession wechatSession = code2OpenId(code);
        if (wechatSession == null) {
            throw new UsernameNotFoundException("非法的微信code");
        }

        User user = userService.getByOpenId(wechatSession.getOpenId());
        // 如果不存在则直接注册
//        if (user == null) {
//            user = new User();
//            user.setOpenId(wechatSession.getOpenId());
//            user.setUnionId(wechatSession.getUnionId());
//            user.setGender(2);
//            userService.signUp(user);
//        }
        if (user == null) {
            throw new UsernameNotFoundException("该微信openId未注册：" + wechatSession.getOpenId());
        }
        AuthenticateUser authenticateUser = new AuthenticateUser();
        authenticateUser.setUsername(integrationAuthentication.getUsername());
        authenticateUser.setPassword(user.getPassword());
        BeanUtils.copyProperties(user, authenticateUser);
        return authenticateUser;
    }

    @Override
    public void prepare(IntegrationAuthentication integrationAuthentication) {

    }

    @Override
    public boolean support(IntegrationAuthentication integrationAuthentication) {
        return AUTH_TYPE.equalsIgnoreCase(integrationAuthentication.getAuthType());
    }

    private WechatSession code2OpenId(String code) {
        return wechatService.code2Session(code);
    }

}
